﻿using System;
using System.Activities;
using System.Activities.Validation;
using System.Collections.Generic;

namespace WFT
{
    /// <summary>
    /// Extension methods for the type Activity
    /// </summary>
    public static class ActivityExtensions
    {
        /// <summary>
        /// Invoke an activity
        /// </summary>
        /// <param name="activity">Activity to invoke</param>
        /// <param name="inputs">Activity inputs</param>
        /// <param name="validateActivity">Defines if the activity should be validated</param>
        /// <returns>Return the outputs of the activity</returns>
        public static IDictionary<string, object> Invoke(
            this Activity activity,
            IDictionary<string, object> inputs = null,
            bool validateActivity = true)
        {
            if (validateActivity)
            {
                ValidationResults validation = ActivityValidationServices.Validate(activity);
                if (validation.Errors.Count > 0)
                    throw new WorkflowApplicationException(
                        String.Format("There is {0} errors in the workflow", validation.Errors.Count));
                if (validation.Warnings.Count > 0)
                    throw new WorkflowApplicationException(
                        String.Format("There is {0} warnings in the workflow", validation.Warnings.Count));
            }

            WorkflowInvoker invoker = new WorkflowInvoker(activity);
            if (inputs != null)
                return invoker.Invoke(inputs);
            else
                return invoker.Invoke();

        }
    }
}
